<template>
  <div>
    <div>
    <el-table
      size="medium"
      class="userBody"
      border
      stripe
      fit
      ref="singleTable"
      :data="userTableData"
      highlight-current-row
      style="width: 100%">
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        property="userCode"
        label="登录名"
        width="120">
      </el-table-column>
      <el-table-column
        property="userName"
        label="姓名"
        width="120">
      </el-table-column>
      <el-table-column
        property="userPhone"
        label="电话"
        width="120">
      </el-table-column>
      <el-table-column
        property="userEmail"
        label="邮箱">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row);dialogFormVisible = true" >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <!--<el-button type="text" @click="handleEdit(scope.$index, scope.row);dialogFormVisible = true" >打开嵌套表单的 Dialog</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    </div>

    <div>
      <el-dialog title="编辑用户" :visible.sync="dialogFormVisible" style="width:80%;margin-left:10%">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" size="small">
          <el-form-item label="登录名" prop="code" :label-width="formLabelWidth">
            <el-input v-model="ruleForm.code" ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" prop="name" :label-width="formLabelWidth" :rules="rules.name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="password" :label-width="formLabelWidth" :rules="rules.password">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="emailNumber" :label-width="formLabelWidth" :rules="rules.emailNumber">
            <el-input v-model="ruleForm.emailNumber"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber" :label-width="formLabelWidth" :rules="rules.phoneNumber">
            <el-input v-model="ruleForm.phoneNumber"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('ruleForm')" size="small">立即修改</el-button>
          <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { mapState} from 'vuex';
  import axios from 'axios';
  import QS from 'qs';


    export default {
      name: "userBody",
      data() {
        return {
          tableData: [],
          userName:'',
          currentRow: null,
          dialogFormVisible: false,
          ruleForm: {
            userid:'',
            code: '',
            name: '',
            password: '',
            emailNumber: '',
            phoneNumber: '',
            region: '',
          },
          formLabelWidth: '80px',

          rules: {
            code: [
              { required: true, message: '请输入登录名', trigger: 'blur' },
              { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
              { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号' }
            ],
            name: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },{
              min: 2,
              max: 5,
              message: '长度在 2 到 5 个字符'
            },{
              pattern: /^[\u4E00-\u9FA5]+$/,
              message: '用户名只能为中文'
            }
              //{ pattern:/^[a-zA-Z]w{1,4}$/, message: '以字母开头，长度在2-5之间， 只能包含字符、数字和下划线'}
            ],
            password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            }, {
              min: 6,
              max: 30,
              message: '长度在 6 到 30 个字符'
            }, {
              pattern: /^(\w){6,20}$/,
              message: '只能输入6-20个字母、数字、下划线'
            }],

            emailNumber: [
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输正确的邮箱地址', trigger: 'blur' }
            ],
            phoneNumber: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'blur'
            },
              {validator:function(rule,value,callback){
                  if(/^1[34578]\d{9}$/.test(value) == false){
                    callback(new Error("请输入正确的手机号"));
                  }else{
                    callback();
                  }
                }, trigger: 'blur'}
            ],
            //   pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
          }
        }
      },
      computed:{
        ...mapState([
          'userTableData',
          'userEditData',
        ])
      },
      methods: {
        handleEdit(index, row) {
          this.$store.commit('userEditMethod',this.userTableData[index]);
              this.ruleForm.code = this.userEditData.userCode;
              this.ruleForm.name = this.userEditData.userName;
              this.ruleForm.password = this.userEditData.userPwd;
              this.ruleForm.emailNumber = this.userEditData.userEmail;
              this.ruleForm.phoneNumber = this.userEditData.userPhone;
              this.ruleForm.userid = this.userEditData.userId;
          // this.$router.push({ path: '/userEdit' });   //跳转到编辑页面的路由，由于页面改造暂行关闭
        },
        handleDelete(index, row) {
          const userid = {}
            userid['SysUserId'] = this.userTableData[index].userId;
          axios.post('/api/sys/sysUser/deleteSysUser',QS.stringify(userid))
            .then(function (response) {
              const data = response.data
              if (data.code == "200"){
                alert('删除成功！');
              }else if (data.code == '201'){
                alert('用户不存在');
              }else{
                alert('删除失败' + '错误代码:' + data.code + '请联系系统管理员！')
              }
            })
            .catch(function (error) {
            });
          this.userTableData.splice(index, 1);  //页面上删除这条数据
        },
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {     //element-ui  表单验证
            const that = this;   //由于this指向已经不是 vue 的对象啦，所以必须重新对this进行定义。
            if (valid) {
              const userform = {};
              userform['userId'] = this.ruleForm.userid;
              userform['userCode'] = this.ruleForm.code;
              userform['userName'] = this.ruleForm.name;
              userform['userPwd'] = this.ruleForm.password;
              userform['userEmail'] = this.ruleForm.emailNumber;
              userform['userPhone'] = this.ruleForm.phoneNumber;
              userform['userGender'] = this.ruleForm.resource;

              axios.post('/api/sys/sysUser/updateSysUser',QS.stringify(userform)) //需要使用QS组件进行包裹，不然无法传值
                .then(function (response) {
                  const data = response.data
                  if (data.code == "200"){
                    alert('修改成功');
                    that.dialogFormVisible = false;
                    that.$emit('clickSearchUser', true);    //调用父组件中的clickSearchUser事件。
                    // that.$router.push({ path: '/user' });     //由于是弹窗，所以不用再进行页面跳转，暂且注释。
                  }else if (data.code == "500"){
                    alert(data.errorMessage);
                  }else{
                    alert('错误代码:' + data.code + '请联系系统管理员！')
                  }
                })
                .catch(function (error) {
                  console.log(error);
                });

            }else {
              console.log('提交失败，请验证数据是否符合规则！');
              // console.log('error submit!!');
              return false;
            }
          });
        },

        resetForm(formName) {
          this.$refs[formName].resetFields();
        },
      },
    }
</script>

<style scoped>
  .userBody{
    margin-top: 10px;
  }
</style>
